<template>
  <div class="promotion-page">
    <div class="chose-board">
      <div class="chose-tabs">
        <div
          class="tabsInfo"
          :style="{ background: tabsShow == 1 ? '#5b55ff' : '#32324e' }"
          @click="choseTabs(1)"
        >
          <p class="tInfoTop">海选晋级</p>
          <p>{{ data.length }}</p>
        </div>
        <div
          class="tabsInfo"
          :style="{ background: tabsShow == 2 ? '#5b55ff' : '#32324e' }"
          @click="choseTabs(2)"
        >
          <p class="tInfoTop">Guest</p>
          <p>{{ dataGuest.length }}</p>
        </div>
        <div
          class="tabsInfo"
          :style="{ background: tabsShow == 3 ? '#5b55ff' : '#32324e' }"
          @click="choseTabs(3)"
        >
          <p class="proTab">对阵图</p>
        </div>
      </div>
    </div>
    <div class="list" style="height: calc(100% - 2rem)">
      <tableCom
        v-if="tabsShow == 1"
        :data="data"
        :column="column"
        :operatesCol="operatesCol"
      >
        <template slot="setInfo" scope="{row}">
          <div :class="['table-com-td', 'item-option']">
            <div class="btn-common del-click-btn" @click="delPromotion(row)">
              移除
            </div>
          </div>
        </template>
      </tableCom>
      <tableCom
        v-if="tabsShow == 2"
        :data="dataGuest"
        :column="columnGuest"
        :operatesCol="operatesColGuest"
      >
        <template slot="option" scope="props">
          <div
            style="width: 100%; display: flex; justify-content: space-between"
          >
            <van-button
              @click="isSure(props)"
              class="blueBtn"
              style="
                width: 45%;
                border-radius: 0.1rem;
                padding: 0.1rem;
                height: 30px;
              "
              color="#2e2e46"
              >确定</van-button
            >
            <van-button
              @click="deleProp(props)"
              style="
                width: 45%;
                border-radius: 0.1rem;
                padding: 0.1rem;
                height: 30px;
              "
              color="#2e2e46"
              >取消</van-button
            >
          </div>
        </template>
      </tableCom>
      <chartCom
        v-if="tabsShow == 3"
        :data="dataChart"
        :column="columnChart"
        :operatesCol="operatesChart"
        @showListDialog="showListDialog"
      ></chartCom>
    </div>
    <div class="homeBtn" v-if="tabsShow == 2">
      <van-button
        style="width: 100%; height: 6.5vh; border-radius: 0.3rem"
        @click="addGuestBtn"
        color="linear-gradient(to right, #5c79f7, #5c74f4)"
        >添加Guest</van-button
      >
    </div>
    <div class="homeBtn" v-if="tabsShow == 3">
      <van-button
        style="width: 100%; height: 6.5vh; border-radius: 0.3rem"
        @click="starAgainst"
        color="linear-gradient(to right, #5c79f7, #5c74f4)"
        >一键生成对阵图</van-button
      >
    </div>
    <!-- 一键生成dialog -->
    <van-popup
      v-model="showPanel"
      closeable
      position="bottom"
      :style="{
        height: '37%',
        background: '#23233b',
        borderRadius: '.2rem .2rem 0 0',
      }"
    >
      <div class="choseMenu">
        <p class="choseTitle">选择生成规则</p>
        <p class="choseTitle">选择生成规则</p>
        <div class="voteStep">
          <van-radio-group
            v-model="level"
            direction="horizontal"
            class="voteStep-radio"
          >
            <van-radio :name="32" class="van-radio-item" icon-size="24px"
              >32强</van-radio
            >
            <van-radio :name="16" class="van-radio-item" icon-size="24px"
              >16强</van-radio
            >
            <van-radio :name="8" class="van-radio-item" icon-size="24px"
              >8强</van-radio
            >
          </van-radio-group>
        </div>
        <p class="choseTitle">选择生成规则</p>
        <div class="voteStep">
          <van-radio-group
            v-model="type"
            direction="horizontal"
            class="voteStep-radio"
          >
            <van-radio :name="1" class="van-radio-item2" icon-size="24px"
              >高低分排位</van-radio
            >
            <van-radio :name="2" class="van-radio-item2" icon-size="24px"
              >随机排位</van-radio
            >
          </van-radio-group>
        </div>
        <div class="votePric">
          <div class="rigPirc">
            <van-button
              color="linear-gradient(to right, #575cfe, #5e80ff)"
              style="border-radius: 0.2rem; width: 100%"
              @click="sponsorAutoAsync"
              >一键生成对阵图</van-button
            >
          </div>
        </div>
      </div>
    </van-popup>

    <!-- 一键生成dialog -->
    <van-popup
      v-model="showPlayerList"
      closeable
      position="bottom"
      :style="{
        height: '70%',
        background: '#23233b',
        borderRadius: '.2rem .2rem 0 0',
        padding: '10px',
      }"
    >
      <div class="player-list-pop">
        <p class="pop-title">选择生成规则</p>
        <div class="player-list-tab">
          <div
            :class="[popActive == 1 ? 'tab-active' : '']"
            @click="popTabChange(1)"
          >
            海选晋级
          </div>
          <div
            :class="[popActive == 2 ? 'tab-active' : '']"
            @click="popTabChange(2)"
          >
            Guest
          </div>
        </div>

        <div class="player-list-table">
          <tableCom
            ref="playerListTable"
            :data="popActive == 1 ? data : dataGuest"
            :column="popActive == 1 ? column : columnGuest"
            :operatesCol="[]"
            :hasOption="false"
          >
          </tableCom>
        </div>

        <div class="player-list-btn">
          <van-button
            style="width: 48%; height: 0.8rem; border-radius: 0.3rem"
            color="linear-gradient(to right, #b267f4, #6953f7)"
            @click="closePop"
            >取消</van-button
          >
          <van-button
            style="width: 48%; height: 0.8rem; border-radius: 0.3rem"
            @click="savePop"
            color="linear-gradient(to right, #5c79f7, #5c74f4)"
            >确定</van-button
          >
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script>
import tableCom from "@/components/tableCom.vue";
import chartCom from "@/components/chartCom.vue";
import {
  scoreUserScore,
  promotionById,
  editGuest,
  deleteGuest,
  addGuest,
} from "@/apis/score";
import {
  vjPrepare,
  sponsorHandler,
  sponsorAutoAsync
} from "@/apis/vj";


export default {
  name: "PromotionPage",
  components: { tableCom, chartCom },
  data() {
    return {
      popActive: 1,
      level: 32,
      type: 1,
      showPanel: false,
      showPlayerList: false,
      tabsShow: 1,
      tabBackColor: 0,
      data: [],
      dataGuest: [],
      dataChart: [],
      column: [
        {
          label: "号码牌",
          prop: "number",
          width: 100,
          isSort: true, // 是否可排序
          SortFun: this.SortCardFun, //排序方法
          SortType: true, //排序状态
          canChange: false, //是否可切换成input框
        },
        {
          label: "总分",
          prop: "score",
          isSort: true,
          SortFun: this.SortAllFun,
          SortType: true,
          canChange: true,
        },
      ],
      columnChart: [
        {
          label: "选手A",
          prop: "playerA",
          width: 100,
          isSort: false, // 是否可排序
          SortFun: this.SortCardFun, //排序方法
          SortType: true, //排序状态
          canChange: true, //是否可切换成input框
        },
        {
          label: "对阵",
          prop: "against",
          isSort: false,
          SortFun: this.SortAllFun,
          SortType: true,
          canChange: false,
        },
        {
          label: "选手B",
          prop: "playerB",
          width: 100,
          isSort: false,
          SortFun: this.SortAllFun,
          SortType: true,
          canChange: true,
        },
      ],
      columnGuest: [
        {
          label: "姓名",
          prop: "name",
          width: 150,
          isSort: false,
          SortFun: this.SortAllFun,
          SortType: true,
          canChange: true,
        },
      ],
      operatesColGuest: [
        {
          name: "修改",
          isShowName: false,
          icon: "records",
          methods: (row) => {
            this.$set(row, "isChange", !row.isChange);
          },
        },
        {
          name: "删除",
          isShowName: false,
          icon: "delete",
          methods: (row) => {
            console.log(row);
            this.$dialog
              .confirm({
                title: `提示`,
                message: `是否删除 ${row.name} guest信息？`,
              })
              .then(async () => {
                const res = await deleteGuest(row.id);
                // deleteGuest().then(() => {
                this.$toast("删除成功");
                this.getGuestList();
                // })
              })
              .catch(() => {});
          },
        },
      ],
      operatesCol: [],
      operatesChart: [],
      curListDialogItem: null
    };
  },
  methods: {
    // 获取海选选手数据
    async getSeaPlayerList() {
      const res = await scoreUserScore(this.$route.query.id, {
        sort: 1,
        isPromotion: 1,
        isGuest: 0,
      });
      this.data = res.result.data;
    },

    // 获取guest数据
    async getGuestList() {
      const res = await scoreUserScore(this.$route.query.id, { isGuest: 1 });
      this.dataGuest = res.result.data.map((item) => {
        item.oldName = item.name;
        return item;
      });
    },
    deleProp(props) {
      if (props.row.isNew) {
        this.dataGuest.splice(props.index, 1);
      } else {
        props.row.name = props.row.oldName;
        this.$set(props.row, "isChange", !props.row.isChange);
      }
    },
    async isSure(props) {
      let params = {
        isGuest: 1,
        name: props.row.name,
        projectId: Number(this.$route.query.id),
      };
      const res = null;
      if (props.row.id) {
        await editGuest(props.row.id, params);
      } else {
        await addGuest(params);
      }
      props.row.isChange = false;
      this.dataGuest[props.index].isNew = false;
    },
    choseTabs(num) {
      this.tabsShow = num;
      this.curListDialogItem = null
      if (this.tabsShow === 1) {
        this.getSeaPlayerList();
      } else if (this.tabsShow === 2) {
        this.getGuestList();
      } else if (this.tabsShow === 3) {
        this.dataChart = [];
        let num = Math.floor((this.data.length + this.dataGuest.length) / 2);
        console.log(num)
        for (let i = 0; i <= num; i++) {
          this.dataChart.push({
            playerA: {
              id: "",
              name: "待定"
            },
            against: "对阵",
            playerB: {
              id: "",
              name: "待定"
            },
          });
        }
        this.getVjPrepare()
      }
    },
    SortCardFun(list, item) {
      item.SortType = !item.SortType;
      this.data = list.sort((a, b) => {
        if (item.SortType) {
          return a.number > b.number ? 1 : -1;
        } else {
          return a.number < b.number ? 1 : -1;
        }
      });
    },
    SortAllFun(list, item) {
      item.SortType = !item.SortType;
      this.data = list.sort((a, b) => {
        if (item.SortType) {
          return a.score > b.score ? 1 : -1;
        } else {
          return a.score < b.score ? 1 : -1;
        }
      });
    },
    addGuestBtn() {
      this.dataGuest.push({ name: "", isChange: true, isNew: true });
    },
    toShare() {
      this.$router.push({
        path: "/scoring/shareBorad",
        query: {},
      });
    },
    // 一键生成对阵图
    starAgainst() {
      this.showPanel = true;
    },
    // 移除已晋级的选手
    async delPromotion(item) {
      this.$dialog
        .confirm({
          title: "提示",
          message: `是否移除${item.number}号选手晋级？`,
        })
        .then(() => {
          promotionById(item.id).then(() => {
            this.$toast.success("修改成功");
            this.getSeaPlayerList();
          });
        })
        .catch(() => {});
    },
    // 获取VJ信息
    async getVjPrepare() {
      const res = await vjPrepare(this.$route.query.id);
        res.result.forEach(resItem=>{
          console.log(this.dataChart, resItem.index)
          if(resItem.index==0) return;
          let num = Math.floor((resItem.index-1)/2)
          if(resItem.index%2 != 0){
            this.dataChart[num].playerA = resItem
          }else{
            this.dataChart[num].playerB = resItem
          }
        })
    },
    showListDialog(val) {
      let arr = [8,16,32]
      let num = this.data.length + this.dataGuest.length
      if(!arr.includes(num)) return this.$toast('当前对阵仅支持32强/16强/8强')
      this.showPlayerList = true;
      this.curListDialogItem = val
    },
    // pop-tab切换
    popTabChange(key) {
      this.popActive = key;
    },
    // pop-保存
    async savePop() {
      console.log(this.curListDialogItem);
      if(!this.$refs.playerListTable.activeRow) return this.$toast('请选择选手')
      let num = this.data.length + this.dataGuest.length
      let posInfo = {
        playerA:1,
        playerB:2,
      }
      let params = {
        index: this.curListDialogItem.index*2+ posInfo[this.curListDialogItem.key],
        level: num,
        userScoreId: this.$refs.playerListTable.activeRowId
      }
      const res = await sponsorHandler(params)
      if(res.code == 1){
        this.$toast(res.message)
        return 
      }
      this.closePop()
    },
    // pop-关闭
    closePop(){
      this.$refs.playerListTable.activeRowId = ''
      this.$refs.playerListTable.activeRow = null
      this.curListDialogItem = null
      this.showPlayerList = false
    },
    // 一键生成对阵图
    async sponsorAutoAsync(){
      let params = {
        level: this.level,
scoreProjectId: Number(this.$route.query.id),
type: this.type
      } 
      const res = await sponsorAutoAsync(params)
      if(res.code == 1){
        this.$toast(res.message)
        return 
      }
        this.dataChart = [];
        let num = Math.floor((this.data.length + this.dataGuest.length) / 2);
        for (let i = 0; i <= num; i++) {
          this.dataChart.push({
            playerA: {
              id: "",
              name: "待定"
            },
            against: "对阵",
            playerB: {
              id: "",
              name: "待定"
            },
          });
        }
      this.showPanel = false
      this.getVjPrepare()

    }
  },
  mounted() {
    this.getSeaPlayerList();
    this.getGuestList();
  },
};
</script>

<style lang="less" scoped>
.blueBtn .van-button__text {
  color: #4982c8;
}

.promotion-page {
  width: 100%;
  height: 100%;
  overflow-y: auto;
  padding: 5px 10px;

  .chose-board {
    .promBtn {
      margin-bottom: 0.3rem;
    }

    .chose-tabs {
      width: 100%;
      display: flex;
      justify-content: space-between;

      .tabsInfo {
        background: #32324e;
        padding: 0.2rem;
        border-radius: 0.05rem;
        width: 2.2rem;
        text-align: center;
        color: rgba(255, 255, 255, 0.8);
        font-size: 0.2rem;

        .proTab {
          width: 100%;
          height: 100%;
          display: flex;
          justify-content: center;
          align-items: center;
        }

        .tInfoTop {
          margin-bottom: 0.2rem;
        }

        .tabStatus {
          background: #2b4856;
          color: #6bc6a2;
          border-radius: 0.2rem;
          width: 80%;
          margin: auto;
        }
      }
    }
  }

  .homeBtn {
    background: #27283d;
    height: 12vh;
    padding: 0 0.2rem;
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .choseMenu {
    color: #fff;
    margin-top: 1rem;
    position: relative;

    .choseTitle {
      font-size: 0.32rem;
      position: absolute;
      top: -0.7rem;
      left: 0.3rem;
    }

    .voteList {
      width: 100%;
      height: 45vh;
      overflow: auto;
    }

    .voteItem {
      width: 90%;
      margin: auto;
      background: #2b2c48;
      border-radius: 0.2rem;
      display: flex;
      padding: 15px;
      min-height: 100px;
      position: relative;
      margin-bottom: 0.2rem;

      .voteLeft {
        display: flex;
        flex-direction: column;
        justify-content: space-between;

        .voteTit {
          font-size: 12px;
          width: 1rem;
          height: 25px;
          text-align: center;
          padding: 5px;
          background: #e645ac;
          border-radius: 5px;
        }

        .voteName {
          font-size: 14px;
        }

        .voteBrief {
          font-size: 12px;
        }
      }

      .votePr {
        position: absolute;
        right: 15px;
        bottom: 15px;
        font-size: 15px;
      }
    }

    .voteStep {
      color: #fff;
      display: flex;
      width: 100%;
      justify-content: space-between;
      padding: 20px 0.2rem 0.2rem 15px;
      .voteStep-radio {
        width: 100%;
        justify-content: space-between !important;
      }
      .van-radio-item {
        background: #191923 !important;
        padding: 15px;
        width: 2rem;
        border-radius: 10px;
        /deep/ .van-radio__label {
          font-size: 18px;
          color: rgba(255, 255, 255, 0.8);
        }
      }
      .van-radio-item2 {
        background: #191923 !important;
        padding: 15px;
        width: 3rem;
        border-radius: 10px;
        /deep/ .van-radio__label {
          font-size: 18px;
          color: rgba(255, 255, 255, 0.8);
        }
      }
      .stepName {
        font-size: 16px;
        margin-bottom: 0.2rem;
      }

      .stepSays {
        font-size: 12px;
      }
    }

    .votePric {
      display: flex;
      justify-content: space-between;
      padding: 0 0.2rem 0.2rem 15px;

      .pricLeft {
        color: #fff;
      }

      .rigPirc {
        width: 100%;
      }
    }
  }
}

.player-list-pop {
  position: relative;
  .pop-title {
    font-size: 0.4rem;
    color: #fff;
    font-weight: bold;
  }
  .player-list-tab {
    display: flex;
    justify-content: space-between;
    margin-top: 10px;
    div {
      background-color: rgba(62, 62, 98, 1);
      border-radius: 6px;
      color: #fff;
      font-size: 0.3rem;
      width: 48%;
      padding: 0.2rem 0.1rem;
      text-align: center;
      font-weight: bold;
    }
    .tab-active {
      background-color: rgba(88, 84, 255, 1);
    }
  }
  .player-list-table {
    width: 100%;
    height: 8.2rem;
    margin-top: 10px;
  }

  .player-list-btn {
    position: fixed;
    bottom: 10px;
    width: 95%;
    display: flex;
    justify-content: space-between;
  }
}
</style>
